package com.yulongtian.offers.day202212;

/**
 * https://leetcode.cn/problems/number-of-islands/?envType=study-plan&id=leetcode_75_level_1&plan=leetcode_75&plan_progress=y7sk2g7
 *
 * @author yulongTian
 * @create 2022-12-27 12:05
 */
public class Test08 {
    public static void main(String[] args) {
        char[][] grid = {
                {'1', '1', '1', '1', '0'},
                {'1', '1', '0', '1', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '0', '0', '0'}
        };
        System.out.println(numIslands(grid));
    }

    public static int numIslands(char[][] grid) {

        int ans = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {

                if (grid[i][j] == '1') {
                    dfs(grid, i, j);
                    ans++;
                }
            }
        }

        return ans;
    }

    public static void dfs(char[][] grid, int cur_i, int cur_j) {
        if (grid[cur_i][cur_j] != '1') {
            return;
        }
        grid[cur_i][cur_j] = '0';


        //上
        if (cur_i - 1 >= 0) {
            dfs(grid, cur_i - 1, cur_j);
        }

        //下
        if (cur_i + 1 < grid.length) {
            dfs(grid, cur_i + 1, cur_j);
        }

        //左
        if (cur_j - 1 >= 0) {
            dfs(grid, cur_i, cur_j - 1);
        }

        // 右
        if (cur_j + 1 < grid[cur_i].length) {
            dfs(grid, cur_i, cur_j + 1);
        }

    }

}
